package com.xiu.travel.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * JWT工具类
 */
public class JwtUtil
{

    //有效期为
    public static final Long JWT_TTL = 30 * 24 * 60 * 60 * 1000L;// 60 * 60 *1000  30个天
    //设置秘钥明文
    public static final String JWT_KEY = "qianlNya";

    public static String getUUID()
    {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 生成jtw
     *
     * @param subject token中要存放的数据（json格式）
     */
    public static String createJWT(String subject)
    {
        // 设置过期时间
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());
        return builder.compact();
    }

    /**
     * 生成jtw
     *
     * @param subject   token中要存放的数据（json格式）
     * @param ttlMillis token超时时间
     * @return String
     */
    public static String createJWT(String subject, Long ttlMillis)
    {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间
        return builder.compact();
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid)
    {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if (ttlMillis == null)
        {
            ttlMillis = JwtUtil.JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)              //唯一的ID
                .setSubject(subject)   // 主题  可以是JSON数据
                .setIssuer("sg")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
                .setExpiration(expDate);
    }

    /**
     * 创建token
     *
     * @param id        id
     * @param subject   subject
     * @param ttlMillis ttlMillis
     * @return createJWT
     */
    public static String createJWT(String id, String subject, Long ttlMillis)
    {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间
        return builder.compact();
    }

    public static void main(String[] args) throws Exception
    {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String p = passwordEncoder.encode("666666");
        System.out.println(p);
//        String jwt = createJWT("2333");
//        System.out.println(jwt);
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2NzNhMjE4OTZmMDA0YzNmOTg2Mzg3ZWYxNmExODg4NCIsInN1YiI6IjE4IiwiaXNzIjoic2ciLCJpYXQiOjE2NzA1MjIyNjEsImV4cCI6MTY3MDUyMjI2MX0.4ChZpRjE9X9Df_78WOKN8CX0rtypi4M0JmugtYtNWq8";
        Claims claims = parseJWT(token);
        System.out.println(claims);
    }

    /**
     * 生成加密后的秘钥 secretKey
     *
     * @return SecretKey
     */
    public static SecretKey generalKey()
    {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY.replace("\r\n", ""));
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    /**
     * 解析
     *
     * @param jwt jwt
     * @return Claims
     * @throws Exception Exception
     */
    public static Claims parseJWT(String jwt) throws Exception
    {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }
}

